#include"tools/log.h"
#include"comm/cpu_instr.h"
#include "tools/klib.h"
#include "stdarg.h"
#include "cpu/irq.h"
#include "ipc/mutex.h"
#include "dev/console.h"
#include "dev/dev.h"

#define LOG_USE_COM 0

static mutex_t mutex;


static int log_dev_id;

#define COM1_PORT 0x3F8
void log_init()
{
    mutex_init(&mutex);

    log_dev_id = dev_open(DEV_TTY,0,(void*)0);
#if LoG_USE_COM
    outb(COM1_PORT + 1, 0x00);    
    outb(COM1_PORT + 3, 0x80);    
    outb(COM1_PORT + 0, 0x03);    
    outb(COM1_PORT + 1, 0x00);    
    outb(COM1_PORT + 3, 0x03);    
    outb(COM1_PORT + 2, 0xC7);   
    outb(COM1_PORT + 4, 0x0F);
#endif
}

void print_log(const char * message, ...) 
{
    char buff[128];
    va_list args;
    kernel_memset(buff,'\0',sizeof(buff));
    //处理参数
    va_start(args,message);
    kernel_vsprintf(buff,message,args);
    va_end(args);

    mutex_lock(&mutex);
#if LoG_USE_COM
    const char * p = buff;
    while (*p != '\0')
    {
        while((inb(COM1_PORT + 5) & (1 << 6)) == 0);
        outb(COM1_PORT, *p++);
    }
 
    outb(COM1_PORT, '\r');
    outb(COM1_PORT, '\n');
#else 
    //console_write(0,buff,kernel_strlen(buff));
    dev_write(log_dev_id,0,"log:",4);
    dev_write(log_dev_id,0,buff,kernel_strlen(buff));
    char c='\n';
    //console_write(0,&c,1);
    dev_write(log_dev_id,0,&c,1);

#endif
    mutex_unlock(&mutex);
}